package com.ccl.iot.views;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.EditText;

import com.ccl.iot.R;
import com.ccl.iot.publics.UIUtils;

/**
 * 显示或隐藏密码的EditText
 */
public class PwdEditText extends EditText {

	private Drawable mDrawableClose, mDrawableOpen;
	private boolean mShowPwd;

	public PwdEditText(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	public PwdEditText(Context context, AttributeSet attrs) {
		this(context, attrs, android.R.attr.editTextStyle);
	}

	public PwdEditText(Context context) {
		this(context, null);
	}

	private void init() {
        mDrawableClose = UIUtils.getContext().getResources().getDrawable(R.drawable.eye_close);
        mDrawableOpen = UIUtils.getContext().getResources().getDrawable(R.drawable.eye_open);
        mDrawableClose.setBounds(0, 0, mDrawableClose.getMinimumWidth()/2, mDrawableClose.getMinimumHeight()/2);
        mDrawableOpen.setBounds(0, 0, mDrawableOpen.getMinimumWidth()/2, mDrawableOpen.getMinimumHeight()/2);
		setCompoundDrawables(null, null, mDrawableClose, null);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			//按下的范围在图片内
			if (getWidth() - event.getX() <= getCompoundPaddingRight()) {
                mDrawableClose.setAlpha(120);
                mDrawableOpen.setAlpha(120);
			}
			break;
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_CANCEL:
            mDrawableClose.setAlpha(255);
            mDrawableOpen.setAlpha(255);
			if (getWidth() - event.getX() <= getCompoundPaddingRight()) {
				if (mShowPwd) {
					setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
					setSelection(getText().length());
                    setCompoundDrawables(null, null, mDrawableClose, null);
					mShowPwd = false;
				} else {
					setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
					setSelection(getText().length());
                    setCompoundDrawables(null, null, mDrawableOpen, null);
					mShowPwd = true;
				}
			}
			break;
		}
		return super.onTouchEvent(event);
	}

}
